package com.xw.service.impl;

import com.xw.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;

/**
 * @Description: 针对表【redis】的数据库操作Service实现
 * @Author: 72478
 * @Date: 2024/12/18 16:53
 * @Version: 1.0
 */
@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String LIKE_PREFIX = "like:";
    private static final String COLLECT_PREFIX = "collect:";

    @Override
    public boolean like(String linkId, String userId) {
        String key = LIKE_PREFIX + linkId;
        SetOperations<String, String> ops = redisTemplate.opsForSet();
        Long result = ops.add(key, userId);
        return result != null && result > 0;
    }

    @Override
    public boolean unlike(String linkId, String userId) {
        String key = LIKE_PREFIX + linkId;
        SetOperations<String, String> ops = redisTemplate.opsForSet();
        Long result = ops.remove(key, userId);
        return result != null && result > 0;
    }

    @Override
    public boolean isLiked(String linkId, String userId) {
        String key = LIKE_PREFIX + linkId;
        return redisTemplate.opsForSet().isMember(key, userId);
    }

    @Override
    public boolean collect(String linkId, String userId) {
        String key = COLLECT_PREFIX + linkId;
        SetOperations<String, String> ops = redisTemplate.opsForSet();
        Long result = ops.add(key, userId);
        return result != null && result > 0;
    }

    @Override
    public boolean uncollect(String linkId, String userId) {
        String key = COLLECT_PREFIX + linkId;
        SetOperations<String, String> ops = redisTemplate.opsForSet();
        Long result = ops.remove(key, userId);
        return result != null && result > 0;
    }

    @Override
    public boolean isCollected(String linkId, String userId) {
        String key = COLLECT_PREFIX + linkId;
        return redisTemplate.opsForSet().isMember(key, userId);
    }

    @Override
    public long getLikesCount(String linkId) {
        String key = LIKE_PREFIX + linkId;
        return redisTemplate.opsForSet().size(key);
    }
}